/**
 * Created by Richard Radlherr.
 * Date: 15.06.2006 02:10
 */

using System;
using TagTool.Core;
using TagTool.GraphicTypes;

namespace TagTool.Nodes.Misc
{

	public class Timer : BaseNode
	{
		private InputSlot interval;
		private InputSlot startStop;
		private OutputSlot tick;

		System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
		
		bool started = true;
		int iv = 1000;
		
		public Timer() : base()
		{
			Name = "Timer";
			interval = new InputSlot(this, "Interval", 1000.0);
			startStop = new InputSlot(this, "Start/Stop", true);
			tick = new OutputSlot(this, "Tick", typeof(bool));
			tick.Value = false;
			timer.Tick += new EventHandler(OnTimerTick);
			interval.ParseCallback = ParseHelper.ParseDouble;
			timer.Interval = (int)((double)interval.Value);
			timer.Start();
		}

		[NodeAttribute(SlotType.Input, Show = true)]
		public InputSlot Interval
		{
			get { return interval; }
		}

		[NodeAttribute(SlotType.Output, Show = true)]
		public OutputSlot Tick
		{
			get { return tick; }
		}

		[NodeAttribute(SlotType.Input, Show = true)]
		public InputSlot StartStop
		{
			get { return startStop; }
		}

		public override void Update(Object sender)
		{
			
			if (iv != (int)(double)interval.Value)
			{
				if (started)
				{
					timer.Stop();
				}
				if ((int)(double)interval.Value <= 10)
			    {
			    	timer.Interval = 10;
			    }
				else
				{
					timer.Interval = (int)((double)interval.Value);
				}
				
				iv = timer.Interval;
				if (started)
				{
					timer.Start();
				}
			}
			
			if (started && !(bool)startStop.Value)
			{
				// stop timer
				timer.Stop();
				started = false;
			}
			else if (!started && (bool)startStop.Value)
			{
				// start timer
				timer.Start();
				started = true;
			}
			
			CastTrigger();
		}

		private void OnTimerTick(Object sender, EventArgs e)
		{
			tick.Value = !(bool)tick.Value;
		}
		
		public override void Initialize()
		{
			timer.Stop();
			
			if ((int)(double)interval.Value <= 10)
		    {
		    	timer.Interval = 10;
		    }
			else
			{
				timer.Interval = (int)((double)interval.Value);
			}
			
			iv = timer.Interval;
			if ((bool)startStop.Value)
			{
				timer.Start();
				started = true;
			}
		}
		
	}
}
